<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Slide\SlideDeleteAction;
use App\Admin\Grid\NGrid;
use App\Library\Logic\OperateLogLogic;
use App\Library\Traits\AdminControllerTrait;
use App\Models\SlideModel;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid\Displayers\Actions;
use Encore\Admin\Grid\Filter;

class SlideController extends AdminController
{
    use AdminControllerTrait;

    protected $title = '轮播图';

    protected function grid(): NGrid
    {
        $grid = new NGrid(new SlideModel);
        $grid->model()->orderBy('sort');
        $grid->filter(function (Filter $filter) {
            $filter->disableIdFilter();
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('id', 'ID')->integer();
                $filter->equal('login', '登录')->select(__('l.whether'));
            });
            $filter->column(1 / 2, function ($filter) {
                $filter->equal('open', '开关')->select([0 => '关闭', 1 => '开启']);
            });
        });
        $grid->column('id', 'ID')->sortable();
        $grid->column('file_id', __('l.fileId'))->display(function ($column) {
            if (!is_null($column)) return view('image', ['id' => $this->id, 'image' => fileIdToUrl($column)]);
            else return null;
        });
        $grid->column('title', __('l.title'));
        $grid->column('link', __('l.link'));
        $grid->column('open', '开关')->using(__('l.openArr'))->label(__('l.openArrLabel'));
        $grid->column('login', '登录')->using(__('l.whether'));
        $grid->column('sort', '排序');
        $grid->disableCreateButton(false);
        $grid->disableActions(false);
        $grid->actions(function (Actions $action) {
            $action->disableDelete();
            $action->add(new SlideDeleteAction);
            $action->disableView();
            $action->disableEdit(false);
        });
        return $grid;
    }

    public function form(): Form
    {
        $form = new Form(new SlideModel);
        $form->hidden('id');
        $form->hidden('file_id');
        $form->hidden('ossPrefix')->default(config('oss.url'));
        $form->ignore(['ossPrefix']);
        $form->text('title', __('l.title'))->attribute('maxlength', 30)->required();
        $form->display('image', '图片上传')->with(function () use ($form) {
            return view('upload_image');
        })->required();
        $form->text('link', __('l.link'));
        $form->select('open', __('l.open'))->options(__('l.openArr'))->required();
        $form->select('login', __('l.login'))->options(__('l.whether'))->required();
        $form->number('sort', __('l.sort'))->required();
        $form->saving(function (Form $form) {
            if (empty($form->file_id)) return $this->backWith('请上传主图');
            return true;
        });
        OperateLogLogic::add(Admin::user()->user_id);
        return $form;
    }
}
